import {nextTick, reactive, ref} from 'vue'
import * as u from '@/util/util'
import {HttpService} from '@/util/httpService'
import {ElMessage, ElMessageBox} from 'element-plus'

const httpService = new HttpService()

export const FUN_TYPE = {
    ADD: 'add',
    DEL: 'del',
    UPDATE: 'update',
    GET_LIST: 'getList'
}


/**
 * table统一封装
 * @param tableOption
 * @param apiUrl
 * @param options
 */
export function useFormMixins(tableOption, apiUrl, options = {}) {
    //表格编辑表单
    const form = ref({})
    //表格请求前置
    const url = ref(apiUrl)
    //新增接口地址
    const addUrl = ref(options.addUrl ?? 'add')
    //修改接口地址
    const updateUrl = ref(options.updateUrl ?? 'update')
    //表格ref
    const refName = ref(options.refName ?? 'crud')
    //查询默认参数
    const defaultParameter = ref(options.defaultParameter ?? {})
    //保存默认参数
    const saveDefaultParameter = ref(options.saveDefaultParameter ?? {})


    // 删除 $ 开头的字段
    const del$ = (obj) => {
        const row = u.copyBean(obj)
        Object.keys(row).forEach(key => {
            if (key.startsWith('$')) {
                delete row[key]
            }
        })
        return row
    }


    //获取id字段
    const getIdField = () => {
        const idCol = tableOption.column.find(col => col.label === 'ID')
        return idCol ? idCol.prop : 'id'
    }

    /**
     * 定义默认保存方法
     * @type {(function(*, *, *): void)|*|(function(*, *, *): void)}
     */
    const handleSave = options.handleSave || ((row, done) => {
        let obj = Object.assign({}, row, saveDefaultParameter.value)
        httpService.post(`/${url.value}/${addUrl.value}`, obj)
            .then(() => {
                ElMessage.success('新增成功')
                done(form)
                //方法执行完毕通知
                funExecuteCompleted(FUN_TYPE.ADD, obj);
            }).catch(() => {
            //方法执行完毕通知
            funExecuteCompleted(FUN_TYPE.ADD, obj);
        })
    })

    /**
     * 定义默认修改方法
     * @type {(function(*, *, *, *): void)|*|(function(*, *): void)|(function(*, *): void)}
     */
    const handleUpdate = options.handleUpdate || ((row, done) => {
        let obj = Object.assign({}, row, saveDefaultParameter.value)
        httpService.put(`/${url.value}/${updateUrl.value}`, obj)
            .then(() => {
                ElMessage.success('修改成功')
                done(form);
                //方法执行完毕通知
                funExecuteCompleted(FUN_TYPE.UPDATE, obj);
            })
            .catch(() => {
                //方法执行完毕通知
                funExecuteCompleted(FUN_TYPE.UPDATE, obj);
            })
    })

    /**
     * 方法执行完毕通知
     * @param funType 方法类型
     * @param obj   返回数据
     */
    const funExecuteCompleted = (funType, obj) => {
        //方法执行完毕，回调通知
        if (options.funExecuteCompleted) {
            options.funExecuteCompleted(funType, obj);
        }
    }

    return {
        form,
        refName,
        handleSave,
        handleUpdate,
        url
    }
}
